import NavStore from './watcher'

const getNextNav = (states, nav) => {
  let nextNav
  states.navs.forEach((v, index) => {
    if (v.value === nav.value) {
      nextNav = states.navs[index + 1] || states.navs[index - 1]
    }
  })
  return nextNav
}

NavStore.prototype.mutations = {
  closeCurrent (states, nav) {
    if (!nav.closeable) return
    let nextNav = getNextNav(states, nav)
    states.navs = states.navs.filter(v => v.value !== nav.value)
    return nextNav
  },
  closeAll (states) {
    states.navs = states.navs.filter(nav => !nav.closeable)
    // 如果还有未关闭的则返回
    return states.navs[0]
  },
  closeOthers (states, nav) {
    states.navs = states.navs.filter(v => v.value === nav.value || !v.closeable)
  },
  remove (states, nav) {
    let nextNav = getNextNav(states, nav)
    states.navs = states.navs.filter(v => v.value !== nav.value)
    return nextNav
  },
  append (states, nav) {
    if ((states.navs || []).findIndex(v => v.value === nav.value) === -1) {
      states.navs.push(nav)
    }
  }
}

NavStore.prototype.commit = function (name, ...args) {
  const mutations = this.mutations
  if (mutations[name]) {
    return mutations[name].apply(this, [this.states].concat(args))
  } else {
    throw new Error(`Action not found: ${name}`)
  }
}

function mapStates (mapper) {
  const res = {}
  Object.keys(mapper).forEach(key => {
    const value = mapper[key]
    let fn
    if (typeof value === 'string') {
      fn = function () {
        return this.store.states[value]
      }
    } else if (typeof value === 'function') {
      fn = function () {
        return value.call(this, this.store.states)
      }
    } else {
      console.error('invalid value type')
    }
    if (fn) {
      res[key] = fn
    }
  })
  return res
}

export {createStore} from './watcher'
export {mapStates}
export default NavStore
